using ColorFillGame.Domain.Entities;
using ColorFillGame.Domain.Repositories;
using ColorFillGame.Domain.Services;
using MediatR;

namespace ColorFillGame.Application.Commands.Game;

public class CreateGameCommandHandler : IRequestHandler<CreateGameCommand, Guid>
{
    private readonly IGameService _gameService;
    private readonly IGameRepository _gameRepository;

    public CreateGameCommandHandler(IGameService gameService, IGameRepository gameRepository)
    {
        _gameService = gameService;
        _gameRepository = gameRepository;
    }

    public async Task<Guid> Handle(CreateGameCommand request, CancellationToken cancellationToken)
    {
        // 创建游戏，传入自定义ID（如果有）
        var game = _gameService.CreateGame(request.Name, request.GridSize, request.MaxPlayers, request.CustomGameId);

        // 保存到仓储
        await _gameRepository.AddAsync(game);
        await _gameRepository.SaveChangesAsync();

        // 返回游戏ID
        return game.Id;
    }
}